<?php
/**
 * Created by PhpStorm.
 * User: zlkmu
 * Date: 2017/10/7
 * Time: 17:41
 * 专门用于处理客户端请求的类
 */

require_once __DIR__.'/../Context/ConnectAPI.php';
require_once __DIR__.'/../Player/PlayerAvatar.php';
require_once __DIR__.'/../Player/User.php';
require_once __DIR__ . '/../Logic/NiuNiuRoomLogic.php';

class ClientRequestProcess{

    /**
     * 处理响应分发的函数
     * @param $connectionID  连接生成的唯一ID
     * @param $clientRequest  \Protocols\GameProtocol解析的协议
     * @param $gameServer   中转服务
     * 参数为：total_length,head_request,status,game_type, client_msg
     */
    public function processClientRequest($connectionID, $clientRequest,$gameServer){
        switch($clientRequest['head_request']) {
            //如果是登录请求
            case ConnectAPI::$LOGIN_REQUEST:
                $this->userLogin($connectionID, $clientRequest,$gameServer);
                break;

            //如果是创建房间请求
            case ConnectAPI::$CREATEROOM_REQUEST:
                $this->createRoom($connectionID,$clientRequest,$gameServer);
                break;

            //加入房间的请求
            case ConnectAPI::$JOIN_ROOM_REQUEST:
                $this->joinRoom($connectionID,$clientRequest,$gameServer);
                break;

            //开始游戏请求(由房主发起)
            case ConnectAPI::$STARTGAME_REQUEST:
                $this->gameStart($connectionID,$clientRequest,$gameServer);
                break;


        }
    }

    /**
     * 处理登录的函数
     * @param $connectionID  客户端连接生成的唯一ID
     * @param $clientRequest 客户端传过来的用户微信信息
     * @param $gameServer 用于数据中转的服务
     */
    private function userLogin($connectionID, $clientRequest,$gameServer){
        $serverContext=$gameServer->serverContext;

        $userModel=new User();
        $userUid=$userModel->judgeUser($clientRequest["client_msg"]);//检查用户是否注册

        if($userUid){
            //当用户已经注册
            $playerAvatar = $serverContext->getPlayerFromOffLine($userUid);//根据user_uid得到玩家的Avatar
            if($playerAvatar){
                //掉线重新连接
                $serverContext->addOnlineCharacter($playerAvatar);
                $serverContext->removeOfflinePlayer($userUid);
                //记录当前connectionID对应的Player在全局SESSION里面
                $_SESSION[$connectionID] = $playerAvatar->getUserID();
            }else{
                //全新登录
                $playerAvatar = new PlayerAvatar($clientRequest['client_msg'], $_SERVER['REMOTE_ADDR']);
                $serverContext->addOnlineCharacter($playerAvatar);
                //记录当前connectionID对应的Player在全局SESSION里面
                $_SESSION[$connectionID] = $playerAvatar->getUserID();
            }

            \GatewayWorker\Lib\Gateway::bindUid($connectionID,$playerAvatar->getUserID());
        }else{
            //用户不存在创建玩家代理   传入玩家微信获取到的信息
            $playerAvatar = new PlayerAvatar($clientRequest['client_msg'], $_SERVER['REMOTE_ADDR']);
            $serverContext->addOnlineCharacter($playerAvatar);
            //记录当前connectionID对应的Player在全局SESSION里面
            $_SESSION[$connectionID] = $playerAvatar->getUserID();
            \GatewayWorker\Lib\Gateway::bindUid($connectionID,$playerAvatar->getUserID());
        }

        //用户登录成功后，将信息发送给玩家
        $gameServer->processServerResponse(ConnectAPI::$LOGIN_RESPONSE,$userUid,$playerAvatar);
    }

    /**
     * 处理创建房间的函数
     * @param $connectionID 客户端连接生成的唯一ID
     * @param $clientRequest 创建房间的数据，对房间进行初始化
     * @param $gameServer 用于数据中转的服务
     */
    private function createRoom($connectionID, $clientRequest,$gameServer) {
        $serverContext=$gameServer->serverContext;
        $niuNiuRoomManager=$gameServer->niuNiuRoomManager;

        //查找到当前创建房间人的UID
        $userUid=$_SESSION["$connectionID"];

        $playerAvatar=$serverContext->getPlayerFromOnLine($userUid);//得到用户Avatar
        $roomId=$niuNiuRoomManager->createNiuNiuRoom($playerAvatar->getUserID(),$clientRequest['client_msg']);//得到牛牛房间ID(参数是一个avatar 和房间相关信息)

        $playerAvatar->setRoomID($roomId);//设置当前玩家的roomId

        //房间创建成功后，将信息发送给玩家
        $gameServer->processServerResponse(ConnectAPI::$CREATEROOM_RESPONSE,$userUid,$roomId);

        var_dump($niuNiuRoomManager->roomList);
    }

    /**
     * 处理加入游戏房间的函数
     * 判断当前房间是否已经开始游戏，并且游戏人数小于6
     * @param $connectionID  客户端连接生成的唯一ID
     * @param $clientRequest 客户端发来的消息  房间ID等等
     * @param $gameServer 用于数据中转的服务
     */
    private function joinRoom($connectionID,$clientRequest,$gameServer){
        $serverContext=$gameServer->serverContext;
        $niuNiuRoomManager=$gameServer->niuNiuRoomManager;
        $serverResponse=$gameServer->serverResponse;

        $userUid=$_SESSION["$connectionID"];//得到玩家uid
        $playerAvatar=$serverContext->getPlayerFromOnLine($userUid);//得到玩家对应的Avatar

        $roomId=$clientRequest["client_msg"]["room_id"];//获取到玩家要加入房间的ID
        $playerAvatar->setRoomID($roomId);//设置玩家的roomID

        $resRoom=$niuNiuRoomManager->getRoom($roomId);//根据房间ID找到对应的房间对象

        if(!$resRoom->getIsBegin()){
            //获取到房间还没开始游戏 再获取房间总人数
            if(count($resRoom->getPlayerList())<6){
                $resRoom->addPlayerToList($playerAvatar->getUserID());//将用户添加到此房间
            }
        }else{
            //房间已经开始，不能加入
        }

        var_dump($resRoom->getPlayerList());
    }

    /**
     * 处理开始游戏的函数（分发牌到此房间里）
     * @param $connectionID  客户端连接生成的唯一ID
     * @param $clientRequest 客户端传过来的用信息 也就是玩家确认开局的请求
     * @param $gameServer 用于数据中转的服务
     */
    private function GameStart($connectionID, $clientRequest,$gameServer){
        $serverContext=$gameServer->serverContext;
        $niuNiuRoomManager=$gameServer->niuNiuRoomManager;
        $serverResponse=$gameServer->serverResponse;

        $userUid=$_SESSION["$connectionID"];//得到玩家uid
        $playerAvatar=$serverContext->getPlayerFromOnLine($userUid);//得到玩家的Avatar对象

        $roomId=$playerAvatar->getRoomID();//得到当前开始游戏的房间号

        $resRoom=$niuNiuRoomManager->getRoom($roomId);//根据房间号得到房间对象

        $playerList=$resRoom->getPlayerList();//得到房间里的所有用户数组ID

        $niuNiuRoom=new NiuNiuRoomLogic();//得到一个游戏处理逻辑


        //遍历房间里的人
        for($i=0;$i<count($playerList);$i++){
            $resPai=$niuNiuRoom->quPai();//得到五张牌

            $playerTemp=$serverContext->getPlayerFromOnLine($playerList[$i]);
            $playerTemp->setPlayerNiuNiuCard($resPai);//给对应房间的玩家设置手中的牌（五张）

            //向各用户分发牌的信息
            $msg["head_code"]=ConnectAPI::$STARTGAME_RESPONSE;
            $msg["status"]=1;
            $msg["game_type"]=0;
            $msg["client_msg"]=json_decode(json_encode($resPai));
            $serverResponse->startGameResponse($playerList[$i],$msg);

        }

        //向各用户分发自己牛的大小
//        for($i=0;$i<count($playerList);$i++){
//            $playerTemp=$serverContext::getPlayerFromOnLine($playerList[$i]);
//            $resMsg=$niuNiuRoom->check($playerTemp->getPlayerNiuniuCard());//得到对应牛的大小
//
//            $msg["head_code"]=ConnectAPI::$STARTGAME_RESPONSE;
//            $msg["status"]=1;
//            $msg["game_type"]=0;
//            $msg["client_msg"]=$resMsg;
//
//            $serverResponse->StartGameResponse($playerTemp->getUserID(),$msg);
//        }
    }


}



?>